import { TransformConfig } from '../types';

export class ComponentTransformer {
  private config: TransformConfig;

  constructor(config: TransformConfig) {
    this.config = config;
  }

  async transformWXML(content: string, filePath: string): Promise<string> {
    // 转换WXML为JSX
    let jsx = this.convertWXMLToJSX(content);
    
    // 生成组件包装
    const componentName = this.getComponentName(filePath);
    
    let component = '';
    if (this.config.typescript) {
      component += `import React from 'react';\n`;
      component += `import { View, Text, Image, ScrollView } from '@tarojs/components';\n\n`;
      component += `interface ${componentName}Props {\n`;
      component += `  // Add your props here\n`;
      component += `}\n\n`;
      component += `const ${componentName}: React.FC<${componentName}Props> = () => {\n`;
    } else {
      component += `import React from 'react';\n`;
      component += `import { View, Text, Image, ScrollView } from '@tarojs/components';\n\n`;
      component += `const ${componentName} = () => {\n`;
    }
    
    component += `  return (\n`;
    component += jsx;
    component += `  );\n`;
    component += `};\n\n`;
    component += `export default ${componentName};\n`;
    
    return component;
  }

  private convertWXMLToJSX(wxml: string): string {
    let jsx = wxml;
    
    // 转换标签名
    jsx = this.transformTags(jsx);
    
    // 转换属性
    jsx = this.transformAttributes(jsx);
    
    // 转换事件
    jsx = this.transformEvents(jsx);
    
    // 转换条件渲染
    jsx = this.transformConditionals(jsx);
    
    // 转换列表渲染
    jsx = this.transformLists(jsx);
    
    return jsx;
  }

  private transformTags(wxml: string): string {
    // 微信小程序标签到Taro组件的映射
    const tagMap: Record<string, string> = {
      'view': 'View',
      'text': 'Text',
      'image': 'Image',
      'scroll-view': 'ScrollView',
      'navigator': 'Navigator',
      'button': 'Button',
      'input': 'Input',
      'textarea': 'Textarea',
      'picker': 'Picker',
      'switch': 'Switch',
      'slider': 'Slider',
      'radio': 'Radio',
      'checkbox': 'Checkbox',
      'form': 'Form',
      'label': 'Label',
      'progress': 'Progress',
      'icon': 'Icon',
      'rich-text': 'RichText',
      'map': 'Map',
      'canvas': 'Canvas',
      'video': 'Video',
      'camera': 'Camera',
      'live-player': 'LivePlayer',
      'live-pusher': 'LivePusher',
      'cover-view': 'CoverView',
      'cover-image': 'CoverImage',
      'movable-view': 'MovableView',
      'movable-area': 'MovableArea',
      'swiper': 'Swiper',
      'swiper-item': 'SwiperItem',
      'block': 'Block'
    };

    let jsx = wxml;
    Object.entries(tagMap).forEach(([oldTag, newTag]) => {
      const regex = new RegExp(`<\\/?${oldTag}`, 'gi');
      jsx = jsx.replace(regex, (match: string) => {
        return match.replace(oldTag, newTag);
      });
    });

    return jsx;
  }

  private transformAttributes(wxml: string): string {
    // 转换属性名
    const attrMap: Record<string, string> = {
      'class': 'className',
      'bindtap': 'onClick',
      'bindtouchstart': 'onTouchStart',
      'bindtouchend': 'onTouchEnd',
      'bindtouchmove': 'onTouchMove',
      'bindinput': 'onInput',
      'bindchange': 'onChange',
      'bindsubmit': 'onSubmit',
      'bindfocus': 'onFocus',
      'bindblur': 'onBlur',
      'bindconfirm': 'onConfirm',
      'bindcancel': 'onCancel',
      'bindlongpress': 'onLongPress'
    };

    let jsx = wxml;
    Object.entries(attrMap).forEach(([oldAttr, newAttr]) => {
      const regex = new RegExp(`${oldAttr}=`, 'gi');
      jsx = jsx.replace(regex, `${newAttr}=`);
    });

    return jsx;
  }

  private transformEvents(wxml: string): string {
    // 转换事件处理
    const eventRegex = /on(\w+)=\{([^}]+)\}/g;
    return wxml.replace(eventRegex, (match, eventName, handler) => {
      return `on${eventName.charAt(0).toUpperCase() + eventName.slice(1)}={${handler}}`;
    });
  }

  private transformConditionals(wxml: string): string {
    // 转换wx:if为条件渲染
    wxml = wxml.replace(/wx:if="([^"]+)"/g, '');
    wxml = wxml.replace(/wx:elif="([^"]+)"/g, '');
    wxml = wxml.replace(/wx:else/g, '');
    
    // 简单的条件渲染转换（需要更复杂的解析）
    return wxml;
  }

  private transformLists(wxml: string): string {
    // 转换wx:for为列表渲染
    wxml = wxml.replace(/wx:for="([^"]+)"/g, '');
    wxml = wxml.replace(/wx:for-item="([^"]+)"/g, '');
    wxml = wxml.replace(/wx:key="([^"]+)"/g, '');
    
    // 简单的列表渲染转换（需要更复杂的解析）
    return wxml;
  }

  private getComponentName(filePath: string): string {
    const fileName = filePath.split('/').pop()?.replace('.wxml', '') || 'Component';
    return fileName.charAt(0).toUpperCase() + fileName.slice(1);
  }
} 